<?php
namespace App\Base;

class AuthController extends \App\Base\ViewController
{
    protected $auth;
    protected $moduleid=0;

    protected function auth(){
        $this->session()->start();
        $admin=$this->session()->get('ADMIN');
        if($admin){
            $admin=json_decode($admin,true);
        }
        
        $this->auth=$admin;
    }

    protected function onRequest($action):?bool
	{
        parent::onRequest($action);
        $this->auth();
        if(!$this->auth) {
            $this->response()->redirect('/welcome/login');
            return false;
        }
        //全局模板变量
        $this->getView()->assign(['ADMIN'=>$this->auth]);

        //check module is exist
        if(in_array($this->MM,['frameset','upload','common'])){
            return true;
        }
        if(!isset($this->CORE_CONF->MAP[$this->MM])){
            $this->msg(0,'模块不存在');
            return false;
        }
        $this->moduleid=$moduleid=$this->CORE_CONF->MAP[$this->MM];
        //check rule is exist
        if(!$this->CORE_CONF->rule_exists($moduleid,$this->AA)){
            $this->msg(0,$this->MM.':'.$this->AA.'权限规则不存在');
            return false;
        }
        if($this->auth['groupid']==1){
            return true;
        }
        if(!$this->CORE_CONF->MODULE[$moduleid]['is_auth']){
            return true;
        }
        if(!$this->CORE_CONF->AUTH[$moduleid][$this->AA]['is_auth']){
            return true;
        }
        //check if has right
        $model=new \App\Model\Access_backModel();
        $d=$model->field('itemid')->where(['userid'=>$this->auth['userid'],'moduleid'=>$moduleid,'module'=>$this->MM,'controller'=>$this->CC,'action'=>$this->AA])->get();
        if(!$d){
            $this->msg(0,'没有权限');
            return false;
        }
	    return true;
    }
    
    protected function afterAction($action):void
    {
        
    }





}